import { useChatMessageStore } from '@/store/chatMessage'
import { useUserStore } from '@/store/user'
import { WSMessageType } from '@/types/ws'
import { getToken } from '@/utils/frontend/token'
import { useEffect, useRef } from 'react'
import { io, Socket } from 'socket.io-client'
import { useChatStore } from '@/store/chat'
import { useRouter } from 'next/navigation'

export function useWebSocket() {
	const socket = useRef<Socket | null>(null)
	const { userInfo } = useUserStore()
	const { addMessage } = useChatMessageStore()
	const router = useRouter()

	// 添加一个消息处理回调函数
	const handleMessage = (data: any) => {
		console.log('接收到新消息', data)
		if (data.chatId && data.id) {
			// 确保消息格式正确
			addMessage(data.chatId, data)
		}
	}

	const handleUserOnlineStatus = (data: any) => {
		console.log('接收到好友在线状态更新', data)
		useChatStore.getState().updateChatStatus(data.friendId, data.status)
	}
	const handlePrivateChat = (data: any) => {
		const { activeChat } = data
		// useChatStore.getState().addChat({
		console.log('接收到聊天室列表更新', activeChat)
		useChatStore.getState().setActiveChat(activeChat)
		router.push(`/im-system/chat/${activeChat.id}`)
	}

	useEffect(() => {
		if (!userInfo?.id || socket.current?.connected) return

		// 建立连接
		socket.current = io(process.env.NEXT_PUBLIC_WS_URL || 'http://localhost:8080', {
			transports: ['websocket'],
			withCredentials: true,
			auth: {
				token: getToken(),
				userId: userInfo.id,
			},
		})

		// 连接事件
		socket.current.on('connect', () => {
			console.log('Connected with socket id:', socket.current?.id)
		})

		// 监听私聊聊天室事件
		socket.current.on(WSMessageType.PRIVATE_CHAT, handlePrivateChat)

		// 监听消息
		socket.current.on(WSMessageType.MESSAGE, handleMessage)

		// 监听用户在线状态
		socket.current.on(WSMessageType.STATUS, handleUserOnlineStatus)

		// 错误处理
		socket.current.on('connect_error', (error) => {
			console.error('Connection error:', error)
		})

		return () => {
			if (socket.current) {
				socket.current.removeAllListeners()
				if (socket.current.connected) {
					socket.current.disconnect()
				}
				socket.current = null
				console.log('WebSocket disconnected')
			}
		}
	}, [userInfo?.id, addMessage])

	const frontendSendWsEvent = (type: WSMessageType, data: any) => {
		if (socket.current?.connected) {
			socket.current.emit(type, data)
		}
	}

	// 添加断开连接的方法

	return { frontendSendWsEvent }
}
